package com.yao2san.simcasclient.authentication.oauth.filter;

import com.alibaba.fastjson.JSONObject;
import com.yao2san.simcasclient.config.ClientConfig;
import com.yao2san.simcasclient.config.ServerConfig;
import com.yao2san.sim.framework.utils.WebUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

public class SimCasOauthFilter implements Filter {
    private ClientConfig clientConfig;
    private ServerConfig serverConfig;

    public SimCasOauthFilter(ClientConfig clientConfig, ServerConfig serverConfig) {
        this.clientConfig = clientConfig;
        this.serverConfig = serverConfig;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (matchExcludeUrls(request)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        System.out.println(JSONObject.toJSONString(clientConfig));
        System.out.println(JSONObject.toJSONString(serverConfig));
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * match should be exclude urls,if matches, return true
     *
     * @param request a request
     * @return if matches, return true,else return false and will not need authentication
     */
    private boolean matchExcludeUrls(HttpServletRequest request) {
        String url = request.getRequestURI();
        List<String> urlExcludes = clientConfig.getUrlExcludes();
        return WebUtil.mathUrl(urlExcludes, url);
    }

    @Override
    public void destroy() {

    }
}
